package http;

import android.util.Log;

import com.dx.as.JWCache;
import com.dx.as.common.CommonUtils;
import com.dx.as.common.JWResult;
import com.dx.as.common.storage.StorageUtil;
import com.dx.as.common.string.StringUtil;
import com.dx.as.utils.Utils;
import com.google.gson.Gson;
import com.google.gson.reflect.TypeToken;
import java.io.IOException;
import java.net.URLDecoder;
import java.net.URLEncoder;
import java.util.concurrent.ExecutorService;
import java.util.concurrent.Executors;

import okhttp3.Interceptor;
import okhttp3.OkHttpClient;
import okhttp3.Request;
import okhttp3.ResponseBody;
import retrofit2.Call;
import retrofit2.Callback;
import retrofit2.Response;
import retrofit2.Retrofit;
import retrofit2.converter.gson.GsonConverterFactory;

/**
 * Created by jwaoo on 2017/5/25.
 */

public class HttpClientHelper {
    private static Retrofit retrofit ;
    private static Gson gson = new Gson();
    public static void doNet(Call call , final IHttpListener listener , TypeToken typeToken){
        CommonUtils.addTypeToken(call.hashCode(),typeToken);
        call.enqueue(new Callback<ResponseBody>() {
            @Override
            public void onResponse(Call<ResponseBody> call, Response<ResponseBody> response) {
                int hasCode = call.hashCode();
                if (response != null && response.isSuccessful()){
                    try {
                        if (response != null) {
                            ResponseBody myResponse = response.body();
                            Log.e("==",""+myResponse.toString());
                            if (myResponse != null){
                                String body = myResponse.string();
                                if (!Utils.isEmpty(body)){
                                     JWResult<Object> result = gson.fromJson(body, CommonUtils.getType(hasCode));
                                     listener.onResponse(result.getRst(),hasCode);
                                }
                            }
                        }
                    }catch (Exception ex){
                        ex.printStackTrace();
                    }
                }else{
                    //统一的错误处理
                }
                CommonUtils.removeTypeToken(hasCode);
            }
            @Override
            public void onFailure(Call<ResponseBody> call, Throwable t) {
                Log.e("==","onFailure");
                if (call != null)
                    CommonUtils.removeTypeToken(call.hashCode());
                if (call != null && !call.isCanceled()){
                    listener.onFailure(t);
                }
                //网络请求失败时总的处理方法
            }
        });
    }

    public static Retrofit getRetrofit(){
        if (retrofit == null){
            retrofit = new Retrofit.Builder()
                    .baseUrl("http://192.168.10.241/")
                    .addConverterFactory(GsonConverterFactory.create())
                    .build(interceptor);
        }
        return retrofit;
    }

    private static Interceptor interceptor = new Interceptor() {
        @Override
        public okhttp3.Response intercept(Chain chain) throws IOException {
            Request original = chain.request();
            // Request customization: add request headers
            Request.Builder requestBuilder = original.newBuilder()
                    .addHeader("client_type","1")
                    .addHeader("device_no", CommonUtils.getDeviceInfo().getDevice_no())
                    .addHeader("mac", CommonUtils.getDeviceInfo().getMac())
                    .addHeader("os_type", CommonUtils.getDeviceInfo().getOs_type())
                    .addHeader("os_version", CommonUtils.getDeviceInfo().getOs_version())
                    .addHeader("hard_ware", CommonUtils.getDeviceInfo().getHard_ware())
                    .addHeader("channel_id", "5969d6211929b03a83578e74")
                    .addHeader("client_id", "5972c401a210fecf8929b714")
                    .addHeader("client_version", CommonUtils.getDeviceInfo().getVersion())
                    .addHeader("network_mode", StringUtil.isEmpty(JWCache.getNetworkMode()) ? "" :JWCache.getNetworkMode())
                    .addHeader("x-auth-token", StringUtil.isEmpty(JWCache.getToken()) ? "" : JWCache.getToken())
                    .addHeader("Content-Type","application/json")
                    .addHeader("hedno","test");//URLEncoder.encode(CommonUtils.getDeviceInfo().getHedno(),"UTF-8"));
            Request request = requestBuilder.build();
            return chain.proceed(request);
        }
    };
}
